package name.weily.liba.widgets

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager

class SingleSelectionRecyclerViewAdapter<T> constructor(
    override val createView: ((parent: ViewGroup, viewType: Int)-> View),
    override val bindVH: ((holder: ViewHolder, item: T?, position: Int)-> Unit))

    : RecyclerViewAdapter<T>(createView, bindVH) {

    constructor() : this(createView = { parent, viewType ->
        LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false)
    }, bindVH = { vh, item, pos ->
        vh.getView<TextView>(android.R.id.text1)?.text = item.toString()
    })

    private var selectionId: Int = -1

    var itemSelectionListener: ((item: View, position: Int, oldSelection: Int) -> Boolean)? = null

    override fun setDataList(list: List<T>) {
        super.setDataList(list)
        selectionId = -1
    }

    override fun removeAt(position: Int) {
        super.removeAt(position)
        if (position == selectionId) {
            selectionId = -1
        }
    }

    override fun clearData() {
        super.clearData()
        selectionId = -1
    }

    override fun onClick(v: View) {
        itemSelectionListener?.apply {
            val tag = v.tag
            if (tag is Int) {
                val old = selectionId
                selectionId = tag
                if (invoke(v, selectionId, old)) {
                    return
                }
            }
        }
        super.onClick(v)
    }

    fun getSelectionId() = selectionId

    fun setSelectionId(recyclerView: RecyclerView, position: Int) {
        if (position <0 || position >= itemCount) {
            return
        }
        when (val layoutManager = recyclerView.layoutManager) {
            is LinearLayoutManager -> {
                val first = layoutManager.findFirstVisibleItemPosition()
                val end = layoutManager.findLastVisibleItemPosition()
                if (position in first..end) {
                    recyclerView.findViewHolderForAdapterPosition(position)?.itemView?.callOnClick()
                } else {
                    recyclerView.scrollToPosition(position)
                    recyclerView.postDelayed({
                        recyclerView.findViewHolderForAdapterPosition(position)?.itemView?.callOnClick()
                    }, 500)
                }
            }
            is GridLayoutManager -> {}
            is StaggeredGridLayoutManager -> {}
        }
    }
}